package com.hospital.shiro;

import com.hospital.pojo.Doctor;
import com.hospital.service.DoctorService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author:晓风残月Lx
 * @Date: 2022/11/19 13:46
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private DoctorService doctorService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 自定义登录认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1.获取用户身份信息
        String userName = authenticationToken.getPrincipal().toString();
        // 2.调用业务层获取数据信息（数据库）
        Doctor doctor = doctorService.getUserInfoByName(userName);
        // 3.非空判断，将数据完成封装返回
        if (doctor != null){
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    doctor,
                    doctor.getPassword(),
                    ByteSource.Util.bytes("salt"),
                    authenticationToken.getPrincipal().toString()
            );
            return info;
        }
        return null;
    }
}
